//
//  RealtimeTranslatorAlertView.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/5/8.
//

import UIKit
import Reusable
import Localize_Swift

extension RealtimeTranslatorAlertView: NibLoadable {}

class RealtimeTranslatorAlertView: UIView {
    
    @IBOutlet weak var bgImageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var contentLabel: UILabel!
    @IBOutlet weak var submitButton: UIButton!
    
    var closeBlock: (() -> Void)?
    
    private var timer: Timer?
    private var totalSecond: Int = 3
    // 获取验证码倒计时秒数
    private var second: Int = 0 {
        didSet {
            if second >= totalSecond || second <= 0 {
                xLog("已经结束了,不做操作")
                
            } else {
                let title = "知道了".localized(.tran) + "（\(second) \("秒".localized(.tran))）"
                submitButton.setTitle(title, for: .normal)
            }
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        if let model = RealtimeTranslationPopupManager.shared.fetch() {
            totalSecond = model.time
            contentLabel.text = model.content
        }
        
        width = xScreenW - 24*2
        
        addRoundedCorners(radius: 12)
        backgroundColor = .clear
        bgImageView.addRoundedCorners(radius: 12)
        
        submitButton.backgroundColor = .gradient(.vertical, colors: [
            UIColor(hex: "#FFA28D"),
            UIColor(hex: "#FF6A00"),
        ], rect: CGRect(x: 0, y: 0, width: (xScreenW - 24*2)*0.5, height: 36))
        
        // 设置阴影颜色
        submitButton.layer.shadowColor = UIColor(hex: "#FF6A00", 0.3).cgColor
        // 设置透明度
        submitButton.layer.shadowOpacity = 6.7
        // 设置阴影半径
        submitButton.layer.shadowRadius = 6
        // 设置阴影偏移量
        submitButton.layer.shadowOffset = CGSize(width: 0, height: 4)
        
        submitButton.layer.cornerRadius = 18
        
        /// 监听语言的变化
        NotificationCenter.default.addObserver(self, selector: #selector(updateLanguageAction), name: NSNotification.Name(LCLLanguageChangeNotification), object: nil)
        updateLanguageAction()
        initTimer()
    }
    
    @IBAction func closeAction(_ sender: UIButton) {
        closeBlock?()
    }
    
    
    // 更新语言
    @objc private func updateLanguageAction() {
        titleLabel.text = "温馨提示".localized(.tran)
        // contentLabel.text = "    " + "环境噪音可能导致识别不准确，影响翻译质量。请尽量在安静环境下使用，确保语音清晰，以获得最佳翻译效果。".localized(.tran)
        
        let height = contentLabel.text!.sg.size(width: xScreenW - 24*4, font: .systemFont(ofSize: 15)).height
        frame = CGRect(x: 0, y: 0, width: xScreenW - 24*2, height: 250 + CGFloat(ceill(Double(height))))
        
    }
    
}

extension RealtimeTranslatorAlertView {
    // MARK: - 初始化定时器
    /// 初始化定时器
    func initTimer() {
        second = totalSecond
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
        if let curTimer: Timer = timer {
            RunLoop.main.add(curTimer, forMode: .common)
        }
        timer?.fire()
    }
    
    // 定时器action
    @objc func timerAction() {
        second = second - 1
        if second <= 0 {
            stopTimer()
            closeBlock?()
        }
    }
    
    // 停止定时
    func stopTimer() {
        if timer != nil {
            second = 0
            timer?.invalidate()
            timer = nil
        }
    }
}
